<?php
/**
 * Description: 个人中心
 * User: wuhao
 * Date: 2017-06-19
 * Time: 15:29
 */
namespace app\backend\controller;
use app\backend\controller\traits\AuthManager;
use app\backend\model\BillManager;
use app\backend\model\Building;
use app\backend\model\Lease;
use app\backend\model\LoginLog;
use app\backend\model\Member;
use app\backend\model\Photo;
use think\Controller;

class UserCenterController extends Controller
{
    use AuthManager;
    private $_memberId = null;
    private $_dtype    = null;
    private $_pdtype   = null;
    private $_pmid     = null;
    private $_allAuth  = [];
    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
        $this->_pdtype   = $memberInfo['p_dtype'];
        $this->_pmid     = $memberInfo['p_mid'];
        $this->_allAuth  = $this->getPower($this->_memberId, $this->_dtype);
    }

    /**
     * 获取个人基本信息
     * @date   2017-6-19
     * @author wuhao
     *
     * @return json
     */
    public function getUserInfo()
    {
        $memberModel   = new Member();
        $loginLogModel = new LoginLog();
        $photoModel    = new Photo();
        //基本信息
        $memberInfo = $memberModel->getMemberInfo(['id' => $this->_memberId], 'username, dtype, mobile');
        if (!$memberInfo) {
            $this->apiReturn(201, [], '查不到相关信息');
        }
        $username = $memberInfo[0]['username'];
        $mobile   = $memberInfo[0]['mobile'];
        //登录日志
        $logInfo = $loginLogModel->getLastLoginLog($this->_memberId);
        //获取图片
        $avatar = $photoModel->getPhoto(['rid'=>$this->_memberId, 'rtype'=>4], 'url');
        if ($avatar) {
            $avatar = $avatar[0]['url'];
        } else {
            $avatar = '';
        }

        //余额
        //$memberMoney = $memberModel->getMemberMoney($this->_memberId);
        //$money = $memberMoney ? yuan($memberMoney) : 0;
        $data = [
            'username'   => $username,
            'mobile'     => $mobile,
            'last_login' => date('Y.m.d H:i:s', $logInfo['login_time']),
            'avatar'     => $avatar,
        ];
        $this->apiReturn(200, $data, '');
    }

    /**
     * 金额统计
     * @date   2017-6-19
     * @author wuhao
     *
     * @param  string  $time     时间
     *
     * @return json
     */
    public function moneySummary()
    {
        if (!in_array($this->_pdtype, [1, 3, 4, 5, 6])) {
            $this->apiReturn(400, [], '无权操作');
        }

        $time = I('post.time', '', 'strval');
        //$time='201706';
        if (!strtotime($time)) {
            $this->apiReturn(400, [], '参数错误');
        }
        $billModel = new BillManager();

        //获取应收的
        $incomeTotal = $incomeActual = 0;
        $bills     = $billModel->getPayBillList(['owner_id' => $this->_pmid, 'bill_time' => $time,  'is_delete' =>0],
            'ordernum, begin_cycle, end_cycle, tenant_id, money, status');
        if ($bills) {
            $incomedMoney = $unIncomedMoney = 0;
            $unPayedId  = $incomedId = [];
            foreach ($bills as $k => $v) {
                if ($v['status'] == 1) {
                    $incomedId[] = $v['ordernum'] . $v['begin_cycle'] . $v['end_cycle'];
                    $incomedMoney += $v['money'];
                } else {
                    $unPayedId[] = $v['ordernum'] . $v['begin_cycle'] . $v['end_cycle'];
                    $unIncomedMoney += $v['money'];
                }
            }


            $incomeTotal  = yuan($incomedMoney + $unIncomedMoney);//总金额
            $incomeActual = yuan($incomedMoney);//已收金额
        }

        //托管运营获取应付的
        $payTotal = $payActual = 0;
        if (in_array($this->_dtype, [3,4])) {
            $bills = $billModel->getAllTrustBill(['tenant_id' => $this->_pmid, 'pay_bill_time' => $time,  'is_delete' => 0],
                'owner_id, tenant_id, ordernum, rent_rate, should_rent, real_rent, share_money, real_share_money, building_id, status');
            if ($bills) {
                //应付房东金额,已付房东金额
               $payMoney = $realPayMoney = 0;
                foreach ($bills as $key => $bill) {
                    //应付房东金额
                    $payMoney += ($bill['should_rent'] - $bill['share_money']);
                    //实付房东金额
                    if ($bill['status'] == 1) {
                        $realPayMoney += ($bill['should_rent'] - $bill['share_money']);
                    }
                }

                $payTotal  = yuan($payMoney);
                $payActual = yuan($realPayMoney);
            }
        }

        $data = [
            'income_total'  => $incomeTotal,
            'income_actual' => $incomeActual,
            'pay_total'     => $payTotal,
            'pay_actual'    => $payActual,
        ];
        $this->apiReturn(200, $data, '');
    }

    /**
     * 获取物业，水电公司，运营方或托管业主对应的楼宇列表
     * @date   2017-06-22
     * @author wuhao
     *
     * @param Building $buildModel  楼宇模型
     * @return array
     */
    private function _getBuilding(Building $buildModel)
    {
        if ($this->_pdtype == 1) {//业主
            $where = ['mid' => $this->_pmid, 'is_delete' => 0];
            $buildingId = $buildModel->getHouseList($where, 'building_id');
            if ($buildingId) {
                $idArr = array_unique(array_column($buildingId, 'building_id'));
                $res = $buildModel->getBuildingList(['id' => ['in', $idArr]], 'id, name');
            } else {
                $res = [];
            }
        } else {
            if ($this->_pdtype == 5) {//物业
                $where = ['property_id' => $this->_pmid, 'is_delete' => 0];
            } elseif ($this->_pdtype == 6) {//水电
                $where = ['hydropower_id' => $this->_pmid, 'is_delete' => 0];
            } elseif ($this->_pdtype == 3 || $this->_pdtype == 4) {//运营方或托管
                $where = ['mid' => $this->_pmid, 'is_delete' => 0];
            }
            $res = $buildModel->getBuildingList($where, 'id, name');
        }

        return $res;
    }

    /**
     * 房源出租情况的统计(饼状图)
     * @date   2017-6-22
     * @author wuhao
     *
     * @return json
     */
    public function houseStatistics()
    {
        if (!in_array($this->_pdtype, [1, 3, 4, 5, 6])) {
            $this->apiReturn(400, [], '无权操作');
        }
        $buildModel   = new Building();
        $leaseModel   = new Lease();
        $expire       = $rent = $unRent = [];
        //获取对应的楼宇信息
        $buildingInfo = $this->_getBuilding($buildModel);
        if (!$buildingInfo) {
            $this->apiReturn(400, [], '无相关房源');
        }
        $buildIdArr = array_column($buildingInfo, 'id');
        //获取对应的房源
        $houseList  = $buildModel->getHouseList(['building_id' => ['in', $buildIdArr], 'is_delete' => 0], 'building_id, mid, house_number, status');
        if (!$houseList) {
            $this->apiReturn(400, [], '无相关房源');
        }

        $sumInfo = [];
        $countExpire = $countRent = $countUnRent = 0;
        foreach ($houseList as $h) {
            if (!isset($sumInfo[$h['building_id']])) {
                $sumInfo[$h['building_id']]['rent'] = 0;
                $sumInfo[$h['building_id']]['un_rent'] = 0;
            }

            if ($h['status'] == 1) {//已出租
                $sumInfo[$h['building_id']]['rent']++;
                $countRent++;
            } else {//未出租
                $sumInfo[$h['building_id']]['un_rent']++;
                $countUnRent++;
            }
        }

        foreach ($sumInfo as $k => $s) {
            foreach ($buildingInfo as $b) {
                if ($k == $b['id']) {
                    $sumInfo[$k]['name'] = $b['name'];
                    break;
                }
            }
        }

        foreach ($sumInfo as $key => $sum) {//取出对应的出租和未出租情况
            $tmpRent = [
                'building_id' => $key,
                'name'        => $sum['name'],
                'sum'         => $sum['rent'],
            ];
            $tmpUnRent = [
                'building_id' => $key,
                'name'        => $sum['name'],
                'sum'         => $sum['un_rent'],
            ];
            $rent[] = $tmpRent;
            $unRent[] = $tmpUnRent;
            unset($tmpRent, $tmpUnRent);
        }

        //获取今日过期的
        $res = $leaseModel->getContractInfo(['building_id'=>['in', $buildIdArr], 'end_time' => date('Ymd'), 'status'=>1], 'ordernum');
        if ($res) {
            $expireOrder = array_column($res, 'ordernum');
            $expireHouse = $leaseModel->getLeaseExtByOrderNum($expireOrder, 'house_number');
            $expireHouse = array_column($expireHouse, 'house_number');
            $houseInfo   = $buildModel->getHouseList(['house_number'=>['in', $expireHouse]], 'building_id, house_number');
           //dd($houseInfo, $buildingInfo);

            foreach ($houseInfo as $h) {
                if (!isset($expire[$h['building_id']])) {
                    $expire[$h['building_id']]['sum'] = 0;
                }
                $expire[$h['building_id']]['sum']++;
                $countExpire++;
            }

            foreach ($expire as $k => $s) {
                $expire[$k]['building_id'] = $k;
                foreach ($buildingInfo as $b) {
                    if ($k == $b['id']) {//获取楼宇名称
                        $expire[$k]['name'] = $b['name'];
                        break;
                    }
                }
            }
            $expire = array_merge($expire);
        }

        $data  = [
            'sum_expire'  => $countExpire,
            'sum_rent'    => $countRent,
            'sum_un_rent' => $countUnRent,
            'expire'      => $expire,
            'rent'        => $rent,
            'un_rent'     => $unRent
        ];
        $this->apiReturn(200, $data, '');
    }

    /**
     * 获取这个收费周期的收入情况（柱状图）
     * @date   2017-6-22
     * @author wuhao
     *
     * @return json
     */
    public function moneyStatistics()
    {
        if (!in_array($this->_pdtype, [1, 3, 4, 5, 6])) {
            $this->apiReturn(400, [], '无权操作');
        }
        $buildModel   = new Building();
        $billModel    = new BillManager();
        //获取对应的楼宇信息
        $buildingInfo = $this->_getBuilding($buildModel);
        if (!$buildingInfo) {
            $this->apiReturn(400, [], '无相关房源');
        }
        $buildIdArr = array_column($buildingInfo, 'id');
        $data = [];
        foreach ($buildingInfo as $b) {
            $data[]  = ['building_id' => $b['id'], 'name'=> $b['name'], 'pay_money' => 0, 'pay_count' =>0, 'un_pay_money' =>0, 'un_pay_count'=>0];
        }

        //获取本周期的账单
        $payBill = $billModel->getPayBillList(['owner_id'=>$this->_pmid, 'bill_time'=> date('Ym'), 'building_id'=>['in', $buildIdArr], 'is_delete'=>0],
            'ordernum, building_id, begin_cycle, end_cycle, money, status');
        if (!$payBill) {
            $this->apiReturn(400, [], '无相关账单');
        }
        $billSum = [];
        foreach ($payBill as $p) {
            if (!isset($billSum[$p['ordernum']])) {
                $billSum[$p['ordernum']]['building_id'] = $p['building_id'];
                $billSum[$p['ordernum']]['money']       = 0;
                $billSum[$p['ordernum']]['status']      = $p['status'];
            }

            $billSum[$p['ordernum']]['money']+= $p['money'];
        }

        foreach ($billSum as $bill) {
            foreach ($data as $k =>  $d) {
                if ($d['building_id'] == $bill['building_id']) {
                    if ($bill['status'] == 0) {//未支付
                        $data[$k]['un_pay_money'] += $bill['money'];
                        $data[$k]['un_pay_count'] ++;
                    } else {
                        $data[$k]['pay_money'] += $bill['money'];
                        $data[$k]['pay_count'] ++;
                    }

                }
            }
        }
        foreach ($data as $a => $b) {
            if ($b['pay_money'] == 0 && $b['un_pay_money'] == 0) {//去除空值
                unset($data[$a]);
            } else {
                //转化为元
                $data[$a]['pay_money']    = yuan($b['pay_money']);
                $data[$a]['un_pay_money'] = yuan($b['un_pay_money']);
            }
        }
        $data = array_merge($data);
        $this->apiReturn(200, $data, '');
    }

    /**
     * 获取提醒的日期 日期图
     * @date   2017-6-23
     * @author wuhao
     *
     * @return json
     */
    public function getNoticeDay()
    {
        $month = date('Ym');
        if ($this->_dtype == 2) {
            //租户获取缴费日期
            $where = ['tenant_id' => $this->_pmid, 'bill_time' => $month, 'status' => 0, 'is_delete' => 0];
        } else {
            //其他用户获取催缴日期
            $where = ['owner_id' => $this->_pmid, 'bill_time' => $month, 'status' => 0, 'is_delete' => 0];
        }
        $billModel = new BillManager();
        $noticeDay = $billModel->getPayBillList($where, 'begin_cycle');
        if (!$noticeDay) {
            $data = [];
        } else {
            $data = array_merge(array_unique(array_column($noticeDay, 'begin_cycle')));
        }

        foreach ($data as $k => $v) {
            $data[$k] = date('d', strtotime($v));
        }

        $this->apiReturn(200, $data, '');
    }

    /**
     * 租户获取
     */
    public function getLeaseBill()
    {
        $status      = I('post.status', 0, 'intval');
        $page        = I('post.page', 1, 'intval');
        $pageSize    = I('post.page_size', 15, 'intval');

        //获取账单列表
        $begin = date('Ymd');
        $billModel = new BillManager();
        $thisMonth = date('Ym', time());//本月
        $nextMonth = date('Ym', strtotime('+1month'));//下月
        $thisTime = $thisMonth.'01';//本月第一天
        $thisEnd  = $thisMonth.date('t', strtotime($thisTime));//本月最后一天
        $nextTime = $nextMonth.'01';//下月第一天
        $nextEnd  = $nextMonth.date('t', strtotime($nextTime));//下月最后一天

        $begin = $thisTime;
        if ($this->_dtype != 2) {//默认查询到当前时间+1月
            $end = $nextEnd;
        } else {//默认查询到当前时间
            $end = $thisEnd;
            //$endMonth = date('Ymd', time());
        }
        //@date 2017-07-10 员工查询房源范围内的账单
        if ($this->_dtype == 7) {
            $auth = $this->houseAuth($this->_memberId);
        } else {
            $auth = []; //其他不做限制
        }

        $res = $billModel->leaseBill($this->_memberId, $this->_pdtype, $this->_dtype, $begin, $end, $status,'', '', $auth, $page, $pageSize);
        if ($res) {
            $buildModel = new Building();
            $leaseModel = new Lease();
            $orderNums  = array_unique(array_column($res, 'contract_id'));

            //获取其他的基本信息
            $billInfo   = $billModel->getPayBillInfo(['ordernum' => ['in', $orderNums], 'is_delete' => 0], 'ordernum, building_id, charge_out, begin_cycle, status');
            $buildingId = array_unique(array_column($billInfo, 'building_id'));
            //获取楼宇名称
            $buildingInfo = $buildModel->getBuildingList(['id' => ['in', $buildingId]], 'id, name');
            //获取对应的房源信息
            $houseNumbers = $leaseModel->getLeaseExtByOrderNum($orderNums, 'ordernum, house_number');

            $houseInfo = [];
            foreach ($houseNumbers as $a => $house) {
                $houseInfo[] = $house['house_number'];
            }
            $houseList = $buildModel->getHouseList(['house_number' => ['in', $houseInfo]], 'house_number, room');
            foreach ($res as $k =>  $v) {
                //获取每条账单对应的账单id数组
                $orderId = $billModel->getBillDetailByOwner($this->_memberId, $this->_dtype, $v['contract_id'], $v['begin_cycle'], $v['end_cycle'], $v['status'], 'id');
                $res[$k]['order_id'] = array_column($orderId, 'id');
                $res[$k]['total_money'] = yuan($v['total_money']);
                $res[$k]['room'] = '';
                //获取账单的对应的房源编号
                foreach ($houseNumbers as $number) {
                    if ($v['contract_id'] == $number['ordernum']) {
                        $res[$k]['house_number'][] = $number['house_number'];
                    }
                }
                //获取房源编号对应的房号
                foreach ($houseList as $h) {
                    if (in_array($h['house_number'], $res[$k]['house_number'])) {
                        $res[$k]['room'] .= $h['room'].',';
                    }
                }
                $res[$k]['room'] = rtrim($res[$k]['room'], ',');
                //获取账单的出账日期和楼宇id
                foreach ($billInfo as  $bill) {
                    if ($bill['ordernum'] == $v['contract_id'] && $bill['begin_cycle'] == $v['begin_cycle'] && $bill['status'] == $v['status']) {
                        $res[$k]['charge_out']  = $bill['charge_out'];
                        $res[$k]['building_id'] = $bill['building_id'];
                        break;
                    }
                }

                //获取对应的楼宇名称
                foreach ($buildingInfo as $build) {
                    if ($build['id'] == $res[$k]['building_id']) {
                        $res[$k]['name'] = $build['name'];
                        break;
                    }
                }
            }
            $sum   = $billModel->countLeaseBill($this->_memberId, $this->_pdtype, $this->_dtype, $begin, $end, $status,'', '', $auth);
            $total = ceil($sum / $pageSize);
            $data  = ['list' => $res, 'current_page' => $page, 'total' => $total];
            $this->apiReturn(200, $data, '');
        } else {
            $this->apiReturn(201, [], '没有数据');
        }
    }
}